/**
 * Created by mar105 on 2019-02-15.
 */

import React, { Component } from 'react';
import { message } from 'antd';
import * as commonConfig from '../../utils/config';
import * as commonUtils from '../../utils/utils';
import * as commonServices from '../../services/services';
import * as commonFunc from './commonFunc'; /* 通用单据方法 */

export default (ChildComponent) => {
  return class extends Component {
    constructor(props) {
      super(props);
      this.state = {
        pageLoading: true,
        token: props.app.token,
        sTabId: this.handleConfigValue('key'),
        sModelsId: this.handleConfigValue('formId'), /* 获取配置数据用的modelId */
        formRoute: this.handleConfigValue('route'), /* 组件名： 路由名称 */
        sModelsType: this.handleConfigValue('sModelsType'), /* 组件名： 路由名称 */
        formData: [], /* 所有配置 */
        gdsformconst: [], /* 获取配置常量 */
        gdsjurisdiction: [], /* 获取配置权限 */
        currentId: props.app.currentPane.checkedId, /* 当前数据的Id */
        selectedRowKeys: [], /*   已选择的数据行(数据格式:数组)   */
      };
    }

    async componentWillMount() {
      /* 获取配置 */
      const { token, sModelsId } = this.state;
      const configUrl = `${commonConfig.server_host}business/getModelBysId/${sModelsId}?sModelsId=${sModelsId}`;
      const configReturn = (await commonServices.getService(token, configUrl)).data;
      if (configReturn.code === 1) {
        const [configData] = configReturn.dataset.rows;
        // const { formData, gdsformconst, gdsjurisdiction, report, billnosetting } = configData;
        this.setState({ ...configData });
      } else {
        this.getServiceError(configReturn);
      }
    }

    shouldComponentUpdate(nextProps, nextState) {
      const currentKey = nextProps.app.currentPane.key; /* 当前页签key */
      const { formData } = nextState;
      return currentKey === nextState.sTabId && formData.length > 0;
    }
    /**   sql条件   */
    getSqlCondition = (showConfig) => {
      const conditonValues = {};
      if (commonUtils.isNotEmptyStr(showConfig.sSqlCondition)) {
        const conditon = showConfig.sSqlCondition.split(',');
        conditon.forEach((item) => {
          if (item.indexOf('.') > -1) {
            const tableName = item.split('.')[0];
            const fieldName = item.split('.')[1];
            const data = this.state[`${tableName}Data`];
            const selectedRowKeys = this.state[`${tableName}SelectedRowKeys`];
            if (typeof data === 'object' && data.constructor === Object) {
              conditonValues[fieldName] = data[fieldName];
            } else if (commonUtils.isNotEmptyArr(selectedRowKeys)) {
              const iIndex = data.findIndex(itemData => itemData.sId === selectedRowKeys[0]);

              if (iIndex > -1) {
                conditonValues[fieldName] = data[iIndex][fieldName];
              }
            }
          }
        });
      }
      return conditonValues;
    };

    /**   获取sql下拉数据   */
    getSqlDropDownData = async (formId, name, showConfig) => {
      /*   地址   */
      const url = `${commonConfig.server_host}business/getSelectDataBysControlId/${showConfig.sId}?sModelsId=${this.state.sModelsId}`;
      /*   参数   */
      const conditonValues = this.getSqlCondition(showConfig);
      const body = {
        sKeyUpFilterName: '', /*   边输入边过滤,暂时没用   */
        sSqlCondition: commonUtils.isEmptyObject(conditonValues) ? '' : conditonValues, /*   查询条件   */
      };
      /*   获取数据   */
      const json = await commonServices.postValueService(this.props.app.token, body, url);
      /*   code为1代表获取数据成功   */
      if (json.data.code === 1) {
        /*   获取数据集   */
        const { rows } = json.data.dataset;
        commonUtils.setStoreDropDownData(formId, name, showConfig.sName, rows);
        return rows;
      } else {
        return [];
      }
    };
    /*   获取数字格式化规范   */
    getFloatNum = (sName) => {
      if (sName.toLowerCase().endsWith('price')) { /*   价格   */
        return this.props.app.decimals.dNetPrice;
      } else if (sName.toLowerCase().endsWith('money')) { /*   金额   */
        return this.props.app.decimals.dNetMoney;
      } else { /*   其它   */
        return 6;
      }
    };

    /**   获取sql下拉数据   */
    getServiceError = async (returnData) => {
      this.props.dispatch({ type: 'app/throwError', payload: returnData });
    };

    /*   获取数字格式化规范   */
    getDateFormat = () => {
      return this.props.app.dateFormat;
    };

    /**   sql下拉新增处理   */
    handleSqlDropDownNewRecord = async (showConfig) => {
      /*   待用数据声明   */
      const sTabId = this.props.app.currentPane.key; /*   当前标签页TabId   */
      /*   接口地址   */
      const sNameUrl = `${commonConfig.server_host}gdsmodule/getGdsmoduleById/${showConfig.sActiveId}?sModelsId=${showConfig.sActiveId}`;
      /*   接口参数   */
      const payload = {
        url: sNameUrl,
        sParentId: sTabId,
      };
      /*   调用接口   */
      this.props.dispatch({ type: 'content/onRouter', payload });
    };

    /* 获取配置数据用的sTabId,formId,formRoute */
    handleConfigValue = (value) => {
      const { secondppopupPane, ppopupPane, currentPane } = this.props.app;
      return commonUtils.isNotEmptyObject(secondppopupPane)
        ? secondppopupPane[value]
        : commonUtils.isNotEmptyObject(ppopupPane)
          ? ppopupPane[value] : currentPane[value];
    };

    /* 获取后台数据（单条） */
    handleGetDataOne = async (params) => {
      const { token, sModelsId } = this.state;
      const {
        name, configData, condition,
      } = params;
      const configDataId = configData.sId;
      const dataUrl = `${commonConfig.server_host}business/getBusinessDataByFormcustomId/${configDataId}?sModelsId=${sModelsId}`;
      const dataReturn = (await commonServices.postValueService(token, condition, dataUrl)).data;
      if (dataReturn.code === 1) {
        const [returnData] = dataReturn.dataset.rows[0].dataSet;
        this.setState({ [`${name}Data`]: returnData });
      } else {
        this.getServiceError(dataReturn);
      }
    };

    /* 获取后台数据（数据集） */
    handleGetDataSet = async (params) => {
      const { token, sModelsId } = this.state;
      const {
        name, configData, condition,
      } = params;
      const configDataId = configData.sId;
      const dataUrl = `${commonConfig.server_host}business/getBusinessDataByFormcustomId/${configDataId}?sModelsId=${sModelsId}`;
      const dataReturn = (await commonServices.postValueService(token, condition, dataUrl)).data;
      if (dataReturn.code === 1) {
        const returnData = dataReturn.dataset.rows[0].dataSet;
        const returnPagination = {
          total: dataReturn.dataset.totalCount,
          current: dataReturn.dataset.currentPageNo,
        };
        const { sumSet } = dataReturn.dataset.rows[0];
        const totalData = sumSet !== undefined ? sumSet : [];
        const filterCondition = commonUtils.isNotEmptyObject(condition) ? condition.bFilter : '';
        const orderBy = commonUtils.isNotEmptyObject(condition) ? condition.sFilterOrderBy : '';
        let addState = {
          [`${name}Data`]: returnData, [`${name}Pagination`]: returnPagination, [`${name}FilterCondition`]: filterCondition, [`${name}OrderBy`]: orderBy,
        };
        if (dataReturn.dataset.currentPageNo === 1) {
          addState = { ...addState, [`${name}Total`]: totalData };
        }
        this.setState(addState);
      } else {
        this.getServiceError(dataReturn);
      }
    };

    /* 数据保存到state */
    handleSaveState = (values) => {
      this.setState(values);
    };

    /** 修改主表数据 */
    handleMasterChange = (name, sFieldName, changeValue, sId, dropDownData, isWait) => {
      let { masterData } = this.state;
      let { handleType } = masterData;
      handleType = commonUtils.isEmpty(handleType) ? 'update' : handleType;
      if (sFieldName.substring(0, 1).toLowerCase() === 'c') {
        const sAllField = sFieldName.substring(1, sFieldName.length);
        const allField = sAllField.split('_');
        const value = changeValue[sFieldName];
        allField.forEach((item, iArr) => {
          if (value.length > iArr) {
            changeValue[item] = value[iArr];
          }
        });
      }
      masterData = { ...masterData, ...changeValue, handleType };
      if (isWait) {
        return { masterData };
      } else {
        this.setState({ masterData });
      }
    };

    /** 表格数据更改 */
    // name 不写完整的state名称作用为了要用到total // (name, changeValue, sId, dropDownData)
    handleTableChange = (name, sFieldName, changeValue, sId, dropDownData, isWait) => {
      const { [`${name}Data`]: tableData } = this.state;
      const iIndex = tableData.findIndex(item => item.sId === sId);
      let { handleType } = tableData[iIndex];
      handleType = commonUtils.isEmpty(handleType) ? 'update' : handleType;
      if (sFieldName.substring(0, 1).toLowerCase() === 'c') {
        const sAllField = sFieldName.substring(1, sFieldName.length);
        const allField = sAllField.split('_');
        const value = changeValue[sFieldName];
        allField.forEach((item, iArr) => {
          if (value.length > iArr) {
            changeValue[item] = value[iArr];
          }
        });
      }
      if (isWait) {
        return { ...tableData[iIndex], ...changeValue, handleType };
      } else {
        tableData[iIndex] = { ...tableData[iIndex], ...changeValue, handleType };
        this.setState({ [`${name}Data`]: tableData });
      }
    };
    /**   添加表格空行   */
    handleTableAdd = (name, isWait) => {
      /*   外置处理业务   */
      const { [`${name}Data`]: tableData, [`${name}Config`]: tableConfig, masterData } = this.state;
      const allTableData = {};
      allTableData.master = masterData;
      const tableDataRow = commonFunc.getDefaultData(tableConfig, allTableData);
      tableDataRow.handleType = 'add';
      tableDataRow.sId = commonUtils.createSid();
      tableDataRow.sParentId = masterData.sId;
      tableDataRow.key = tableDataRow.sId;
      tableDataRow.bDefault = false;
      const { sModelsType, formId } = this.props.app.currentPane;
      if (sModelsType === 'element/materialsInfo') {
        tableDataRow.sFormId = formId;
        tableDataRow.sMaterialsId = masterData.sId;
      } else if (sModelsType === 'element/printInfo') {
        tableDataRow.sFormId = formId;
        tableDataRow.sProductId = masterData.sId;
        tableDataRow.sCustomerId = masterData.sCustomerId;
      }
      if (isWait) {
        return tableDataRow;
      } else {
        tableData.push(tableDataRow);
        this.setState({ [`${name}Data`]: tableData });
      }
    };

    // name 不写完整的state名称作用为了要用到total
    /**   删除表格数据   */
    handleTableDel = (name, isWait) => {
      const { app } = this.props;
      const { [`${name}Data`]: tableData, [`${name}SelectedRowKeys`]: tableSelectedRowKeys } = this.state;
      let { [`${name}DelData`]: tableDelData } = this.state;
      tableDelData = commonUtils.isEmptyArr(tableDelData) ? [] : tableDelData;
      if (commonUtils.isNotEmptyArr(tableSelectedRowKeys)) {
        for (const sId of tableSelectedRowKeys) {
          /*   看看删除集合和从表中是否都存在该条数据   */
          let tableDataIndex = tableData.findIndex(item => item.sId === sId);
          while (tableDataIndex > -1) {
            /*   删除从表中的数据并存入删除集合中   */
            const slaveDataFilter = tableData[tableDataIndex];
            tableData.splice(tableDataIndex, 1);
            slaveDataFilter.handleType = 'del';
            tableDelData.push(slaveDataFilter);
            tableDataIndex = tableData.findIndex(item => item.sId === sId);
          }
        }
        if (isWait) {
          return { [`${name}Data`]: tableData, [`${name}DelData`]: tableDelData, [`${name}SelectedRowKeys`]: [] };
        } else {
          this.setState({ [`${name}Data`]: tableData, [`${name}DelData`]: tableDelData, [`${name}SelectedRowKeys`]: [] });
          return true;
        }
      } else {
        message.warn(commonFunc.showMessage(app.commonConst, 'pleaseChooseDelData')); // 请选择删除数据
        return false;
      }
    };

    /**   处理选择行发生改变   */
    handleTableSelectRowChange = (name, selectedRowKeys) => {
      /*   外置处理业务   */
      const { formRoute, slaveData } = this.state;
      let { slaveSelectedData } = this.state;
      const addState = {};
      addState[`${name}SelectedRowKeys`] = selectedRowKeys;
      addState.searchUpDownData = {};
      if (name === 'slave' && formRoute === '/commonList') {
        const slavePageData = slaveData.filter(item => selectedRowKeys.includes(item.sSlaveId));
        slaveSelectedData = commonUtils.isEmpty(slaveSelectedData) ? [] : slaveSelectedData.filter(item => selectedRowKeys.toString().includes(item.sSlaveId));
        selectedRowKeys.forEach((item) => {
          const iIndex = slaveSelectedData.findIndex(selectItem => selectItem.sSlaveId === item);
          if (iIndex === -1) {
            const iPageIndex = slavePageData.findIndex(pageItem => pageItem.sSlaveId === item);
            if (iPageIndex > -1) {
              slaveSelectedData.push(slavePageData[iPageIndex]);
            }
          }
        });
        addState.slaveSelectedData = slaveSelectedData;
      }
      this.setState(addState);
    };

    render() {
      return (
        <div>
          <ChildComponent
            {...this.props}
            {...this.state}
            getSqlDropDownData={this.getSqlDropDownData}
            getSqlCondition={this.getSqlCondition}
            getServiceError={this.getServiceError}
            handleSqlDropDownNewRecord={this.handleSqlDropDownNewRecord}
            getFloatNum={this.getFloatNum}
            getDateFormat={this.getDateFormat}
            handleGetDataOne={this.handleGetDataOne}
            handleGetDataSet={this.handleGetDataSet}
            onSaveState={this.handleSaveState}
            onChange={this.handleMasterChange}
            onDataChange={this.handleTableChange}
            onDataRowAdd={this.handleTableAdd}
            onDataRowDel={this.handleTableDel}
            onTableSelectRowChange={this.handleTableSelectRowChange}
          />
        </div>
      );
    }
  };
};
